<template>
  <div class="my">
    <div class="header" :style="{ background: `url(${resources.userBg})` }">
      <div class="info">
        <div class="avatar" @click="showAvatar">
          <img :src="userInfo.avatar || resources.defaultAvatar" alt="" />
        </div>
        <div class="nickname" @click="goToLogin">
          {{ userInfo.nickname || "立即登录" }}
        </div>
      </div>
      <div class="setting">
        <van-icon name="setting-o" @click="$router.push('/setting')" />
      </div>
    </div>
    <div class="date">
      <el-calendar>
        <template slot="dateCell" slot-scope="{ date, data }">
          <p
            :class="data.isSelected ? 'is-selected' : ''"
            style="height: 100%"
            @click="
              toDetail(
                data.day,
                signDateList.find((item) => item.date === data.day)
              )
            "
          >
            {{ data.day.split("-").slice(2).join("-") }}
            {{
              signDateList.some((item) => item.date === data.day) ? "✔️" : ""
            }}
            <span
              style="
                margin-top: 2px;
                display: inline-block;
                font-size: 10px;
                font-weight: 600;
              "
              >{{
                signDateList.some((item) => item.date === data.day)
                  ? `${signDateList
                      .find((item) => item.date === data.day)
                      .duration.toFixed(1)}分钟`
                  : ""
              }}</span
            >
          </p>
        </template>
      </el-calendar>
    </div>
    <div class="detail">
      <div class="statistic">
        <div class="total-duration">
          总时长：{{ totalDuration.toFixed(1) }}分钟
        </div>
        <div class="first-sport">
          最高时长运动：{{ maxDurationSport || "暂无" }}
        </div>
      </div>
      <div class="container">
        <div class="records" v-if="sportList.length > 0">
          <van-sticky>
            <div class="item-header">
              <div>类型</div>
              <div>时长</div>
              <div>数据</div>
            </div>
          </van-sticky>
          <div class="item" v-for="item in sportList" :key="item.id">
            <div class="type">{{ item.sportType }}</div>
            <div class="duration">
              {{ `${item.hours}:${item.minutes}:${item.seconds}` }}
            </div>
            <div class="data">{{ formatData(item) }}</div>
          </div>
        </div>
        <van-empty description="暂无记录" v-else />
      </div>
    </div>
  </div>
</template>

<script>
import { ImagePreview, Toast } from "vant";
import userModule from "@/utils/userInfo";
import { getSignList } from "@/api/mobile/sign";
import { getDetail } from "@/api/mobile/sport";
import modifyActivityTime from "@/utils/modify";
import { getList } from "@/api/mobile/resources";
export default {
  name: "MyView",
  data() {
    return {
      userInfo: {},
      signList: [],
      signDateList: [],
      totalDuration: 0,
      maxDurationSport: "",
      sportList: [],
      resources: {},
    };
  },
  created() {
    this.getUserInfo();
    this.getSignList();
    this.getResources();
  },
  methods: {
    async getResources() {
      const res = await getList();
      this.resources = res.data;
      console.log();
    },
    // 显示头像
    showAvatar() {
      ImagePreview([this.userInfo.avatar || this.defaultAvatar]);
    },
    // 去登陆
    goToLogin() {
      if (Object.keys(this.userInfo).length === 0) {
        this.$router.push("/login");
      }
    },
    // 获取用户信息
    getUserInfo() {
      const user = userModule.getUser();
      if (user) {
        this.userInfo = user;
      }
    },
    // 获取用户签到列表
    async getSignList() {
      const res = await getSignList({ id: this.userInfo.id });
      this.signList = res.data;

      this.signList.forEach((item) => {
        const formattedDate = item.signDate
          .map((num, index) => {
            // 对于月份和日期，确保它们是两位数
            if (index > 0) {
              // 月份和日期在数组的第二个和第三个位置
              return num.toString().padStart(2, "0");
            }
            return num;
          })
          .join("-");
        this.signDateList.push({
          sportId: item.sportId,
          date: formattedDate,
          duration: item.duration,
        });
        this.totalDuration += item.duration;
      });
      // 更新用户活动时间
      modifyActivityTime();
    },
    // 查看签到详情
    async toDetail(date, item) {
      // 选择的时间
      const selectDateTimestamp = +new Date(date);
      // 当前时间
      const currentTimestamp = +new Date();
      if (selectDateTimestamp > currentTimestamp) {
        Toast.fail("时间还未到");
        return;
      }
      // 对比查询是否选择的时间是否在数据集中
      if (!this.signDateList.some((item) => item.date === date)) {
        Toast.fail("未签到");
        return;
      }
      // 查询运动详情
      const res = await getDetail({ id: item.sportId });
      this.sportList = res.data;

      if (this.sportList.length > 0) {
        const timeArr = this.sportList.map((item) => {
          return (
            (item.hours < 10 ? `0${item.hours}` : item.hours) +
            "-" +
            (item.minutes < 10 ? `0${item.minutes}` : item.minutes) +
            "-" +
            (item.seconds < 10 ? `0${item.seconds}` : item.seconds)
          );
        });

        // 升序排列
        timeArr.sort();

        // 获取排序后的最后一个数据
        this.maxDurationSport = this.sportList.find(
          (item) =>
            (item.hours < 10 ? `0${item.hours}` : item.hours) +
              "-" +
              (item.minutes < 10 ? `0${item.minutes}` : item.minutes) +
              "-" +
              (item.seconds < 10 ? `0${item.seconds}` : item.seconds) ===
            timeArr[timeArr.length - 1]
        ).sportType;
      } else {
        this.maxDurationSport = "";
      }
    },
    // 格式化运动数据
    formatData(item) {
      return item.data + this.judgmentType(item.metricType);
    },
    judgmentType(type) {
      switch (type) {
        case "distance":
          return "km";
        case "count":
          return "个";
        default:
          return "--";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.my {
  padding-bottom: 60px;
  min-height: 100vh;
  .header {
    display: flex;
    padding: 0 10px;
    height: 180px;
    background: linear-gradient(
      to right bottom,
      rgba(255, 216, 185, 0.89),
      transparent
    );
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    .info {
      display: flex;
      align-items: center;
      width: 90%;
      height: 100%;
      .avatar {
        width: 80px;
        height: 80px;
        border: 1px solid #ccc;
        border-radius: 50%;
        img {
          width: 100%;
          height: 100%;
          border-radius: inherit;
        }
      }
      .nickname {
        margin-left: 6px;
        width: calc(100% - 90px);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 600;
        font-size: 20px;
        color: #fff;
      }
    }
    .setting {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      padding-top: 20px;
      font-size: 26px;
      color: #fff;
    }
  }
  .date {
    height: 300px;
  }
  .detail {
    margin: 10px 10px 0;
    padding: 10px;
    min-height: 50px;
    border-radius: 10px;
    background-color: #fff;
    .statistic {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #333;
      .total-duration,
      .first-sport {
        width: 48%;
      }
    }
  }
  .container {
    .records {
      margin: 20px 0;
      h4 {
        font-size: 18px;
        padding-bottom: 4px;
      }
      .item-header {
        display: flex;
        height: 30px;
        text-align: center;
        border-radius: 8px;
        div:nth-child(1),
        div:nth-child(2),
        div:nth-child(3) {
          width: 33%;
        }
      }
      .item {
        display: flex;
        margin: 10px 0;
        box-shadow: 0 0 4px #ccc;
        border-radius: 10px;
        text-align: center;
        height: 40px;
        line-height: 40px;
        .type,
        .duration,
        .data {
          width: 33%;
        }
      }
    }
  }
}
.is-selected {
  color: #1989fa;
}
/deep/.el-calendar {
  height: 100%;
}
/deep/.el-calendar__body {
  height: calc(100% - 50px);
  background-color: #fff;
  font-size: 12px;
  overflow-y: auto;
}
/deep/.el-calendar-table {
  thead {
    position: sticky;
    top: -12px;
    background-color: #fff;
  }
  tbody {
    tr {
      height: 40px;
    }
  }
}
</style>